package controller

import (
	"admin/app/http/response"
	"admin/app/service"
	"admin/constant"
	"admin/tools"
	"fmt"
	"github.com/gin-gonic/gin"
)

type LoginController struct {
}

func LoginRegister(LoginGrp *gin.RouterGroup) {
	loginController := &LoginController{}
	LoginGrp.Use().POST("/login", loginController.login)
}

/*
* 用户登录
 */
func (c LoginController) login(ctx *gin.Context) {

	var body struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	if err := ctx.BindJSON(&body); err != nil {
		return
	}

	user := service.GetUserByName(body.Username, body.Password)
	if user != nil {
		fmt.Println(user.ID)
		token, err := tools.GenerateJWT(*user)
		if err != nil {
			response.Success(ctx, constant.SelectSuccessCode, constant.SelectSuccessMsg, gin.H{"token": user.Name})
		}
		response.Success(ctx, constant.SelectSuccessCode, constant.SelectSuccessMsg, gin.H{"token": token})
	} else {
		response.Success(ctx, 10001, "用户名或密码不正确", gin.H{})
	}

}
